﻿(function () {
    'use strict';
    angular.module('app').controller('loginCtrl', ['$scope','$timeout', 'loginSrvc',
        function ($scope, $timeout, loginSrvc) {

            activate();

            function activate() {
                $timeout(function () {
                    angular.element('#username').focus();
                });
            };


            $scope.forms = {
                isForgot: false,
                isLogin: true,
                isRegister:false
            };
            $scope.loginError =
            {
                status: false,
                desc: ''
            };

            $scope.openforms = function (form) {
                switch (form) {
                    case 'forgot':
                        $scope.forms.isForgot = true;
                        $scope.forms.isLogin = false;
                        $scope.forms.isRegister = false;
                        break;
                    case 'login':
                        $scope.forms.isForgot = false;
                        $scope.forms.isLogin = true;
                        $scope.forms.isRegister = false;
                        break;
                    default:
                        $scope.forms.isForgot = false;
                        $scope.forms.isLogin = false;
                        $scope.forms.isRegister = true;
                }
            };
            $scope.loginCredentials = {
                username: '',
                password:''
            };
            $scope.login = function () {
                var credentials = 'username=' + $scope.loginCredentials.username;
                credentials = credentials + '&password=' + $scope.loginCredentials.password;
                credentials = credentials + '&grant_type=password';

                loginSrvc.login(credentials).then(function (data) {
                    var userInfo = {
                        User: $scope.loginCredentials.username,
                        Password: $scope.loginCredentials.password,
                        Token: data.access_token
                    };
                    loginSrvc.setToken(userInfo).then(function () {
                        window.location.href = '/Dashboard';
                    });
                }, function (data) {
                    angular.element('#username').focus();
                    $scope.loginError.status = true;
                    $scope.loginError.desc = data.error_description;
                });
            };
    }]);

})();